package cn.nchelj.ueditor.controller;

import java.io.*;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.nchelj.ueditor.dto.UeditorConfig;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class UeditorContorller {
    private static final Logger log = LoggerFactory.getLogger(UeditorContorller.class);
    private String configJsonParentPath ="";
    @Value("${web.upload-path}")
    private String fileRelativePath;
    @Value("${server.port}")
    private String lsport;

    @RequestMapping("/")
    public String getAddress() {
        System.out.println("进入页面");
        return "index";
    }

    /**
     * 根目录请求
     * @author helj
     * @date 2020年12月29日 上午11:22:47
     * @version V1.0
     */
    @ResponseBody
    @RequestMapping("ueditor")
    public Object ueditorConfig(MultipartFile upfile, HttpServletRequest request, HttpServletResponse response, String action) {

        switch (action) {
            case "config":
                log.info("读取config.json");
                Object uEditorConfig = this.getUEditorConfig(response);
                return uEditorConfig;
            case "uploadimage":
            case "uploadscrawl":
            case "catchimage":
            case "uploadvideo":
            case "uploadfile":
            case "listimage":
            case "listfile":
                log.info("文件上传");
                String returnJson = this.uploadfile(upfile, request, response);
                return returnJson;
        }
        return "请求失败";
    }

    /**
     * 读取ueditor/config.json
     * @author helj
     * @date 2020年12月29日 上午11:22:47
     * @version V1.0
     */
    public Object getUEditorConfig(HttpServletResponse response) {
        try {
            String os = System.getProperty("os.name");//判断操作系统
            if(os.toLowerCase().startsWith("win")){
                configJsonParentPath = ClassUtils.getDefaultClassLoader().getResource("").getPath() + "static/ueditor";
            }
            else {
                configJsonParentPath = fileRelativePath+"/ueditor";
            }

            response.setContentType("application/json;charset=utf-8");
            return readTxt(new File(configJsonParentPath+"/jsp/config.json"));

        } catch (Exception e) {
            log.error("读取ueditor/config.json异常" + e);
            return "error";
        }
    }

    /**
     * 读取文件
     * @param file
     * @return
     * @throws IOException
     */
    public static String readTxt(File file) throws IOException {
        String s = "";
        InputStreamReader in = new InputStreamReader(new FileInputStream(file),"UTF-8");
        BufferedReader br = new BufferedReader(in);
        StringBuffer content = new StringBuffer();
        while ((s=br.readLine())!=null){
          content = content.append(s);
        }
      return content.toString();
    }

    /**
     * 上传图片
     * @author helj
     * @date 2020年12月29日 上午11:22:47
     * @version V1.0
     */
    public String uploadfile(MultipartFile upfile, HttpServletRequest request, HttpServletResponse response) {
        UeditorConfig ueditorConfig = new UeditorConfig();
        try {
            try {
                String os = System.getProperty("os.name");//判断操作系统
                if(os.toLowerCase().startsWith("win")){
                    configJsonParentPath = "E:/ueditor/uploadfile/";
                }
                else {
                    configJsonParentPath = fileRelativePath;
                }
                String fileName = upfile.getOriginalFilename();
                String suffixName = fileName.substring(fileName.lastIndexOf("."));
                fileName = UUID.randomUUID()+suffixName;
                String visitUrl = "http://localhost:"+lsport+"/"+fileName;
                //自定义存放路径

                try {
                    upfile.transferTo(new File(configJsonParentPath+fileName));
                } catch (Exception e) {
                    e.printStackTrace();
                }

                // 返回状态码
                ueditorConfig.setState("SUCCESS");
                ueditorConfig.setUrl(visitUrl);
                ueditorConfig.setSize(upfile.getSize());
                ueditorConfig.setOriginal(fileName);
                ueditorConfig.setType(upfile.getContentType());

            } catch (Exception e) {
                e.printStackTrace();
            }

        } catch (Exception e) {
            e.printStackTrace();
            ueditorConfig.setState("ERROR");
        }
        String returnJson =  JSON.toJSONString(ueditorConfig);
        log.info("图片上传返回字符===>>>" + returnJson);
        return returnJson;
    }
}
